import 'package:flutter/material.dart';
import 'package:shining_red_star/model/unique.dart';

import '../definitions/color.dart';
import '../definitions/system_aud.dart';
import '../utils/play.dart';
import 'auto_grid.dart';
import 'focus_manage/focus_widget.dart';

class ChoiceQuestion<T extends Unique> extends StatefulWidget {
  final List<T> options;
  final T answer;
  final Widget Function(T answer, List<T> options, bool hasFocus)
      renderQuestion;
  final Widget Function(T option, bool hasFocus) renderOption;
  final String Function(T answer, List<T> options) getQuestionAud;
  final Function(bool isRight)? onAnswered;
  final void Function()? nextQuestion;

  const ChoiceQuestion({
    super.key,
    required this.renderQuestion,
    required this.options,
    required this.answer,
    required this.renderOption,
    required this.getQuestionAud,
    this.onAnswered,
    this.nextQuestion,
  });

  @override
  State<ChoiceQuestion<T>> createState() => _ChoiceQuestionState();
}

class _ChoiceQuestionState<T extends Unique> extends State<ChoiceQuestion<T>> {
  T? activeOption;
  bool? isRight;
  List<FocusNode> focusNodes = [FocusNode(), FocusNode()];

  void playQuestionAud() {
    AudioPlayManager.lowLatencyPlay(
        widget.getQuestionAud(widget.answer, widget.options));
  }

  @override
  void initState() {
    super.initState();
    focusNodes
        .addAll(List.generate(widget.options.length, (index) => FocusNode()));
    playQuestionAud();
  }

  @override
  void didUpdateWidget(covariant ChoiceQuestion<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.answer.id != widget.answer.id) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        setState(() {
          activeOption = null;
          isRight = null;
        });
        playQuestionAud();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
            margin: EdgeInsets.only(bottom: 20),
            child: FocusWidget(
              autofocus: true,
              focusNode: focusNodes[0],
              onConfirm: playQuestionAud,
              onFocusChange: (bool value) {
                setState(() {});
              },
              child: widget.renderQuestion(
                  widget.answer, widget.options, focusNodes[0].hasFocus),
            )),
        Expanded(
          child: AutoGrid(
            expectItemWidth: 150,
            expectItemHeight: 200,
            getExpectRowCount: (constraints) {
              if (constraints.maxWidth > constraints.maxHeight) {
                return 4;
              }
              return 2;
            },
            calcHeight: (itemWidth) {
              return itemWidth + 32;
            },
            mainAxisSpacing: 12,
            crossAxisSpacing: 12,
            children: widget.options.map((item) {
              FocusNode focusNode =
                  focusNodes[widget.options.indexOf(item) + 2];
              List<Widget> showOption = [
                widget.renderOption(item, focusNode.hasFocus)
              ];
              if (activeOption?.id == item.id && isRight != null) {
                showOption.add(Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Colors.black.withAlpha(80),
                  ),
                  child: Icon(
                    isRight! ? Icons.check_circle : Icons.cancel,
                    color: isRight! ? Colors.green : Colors.red,
                    size: 48,
                  ),
                ));
              }
              return FocusWidget(
                focusNode: focusNode,
                onFocusChange: (bool value) {
                  setState(() {});
                },
                onConfirm: () {
                  if (activeOption != null) {
                    return;
                  }
                  bool currentIsRight = item.id == widget.answer.id;
                  if (currentIsRight) {
                    AudioPlayManager.lowLatencyPlay(SystemAud.right.value);
                    widget.onAnswered?.call(true);
                  } else {
                    AudioPlayManager.lowLatencyPlay(SystemAud.wrong.value);
                    widget.onAnswered?.call(false);
                    Future.delayed(Duration(seconds: 1), () {
                      setState(() {
                        activeOption = null;
                        isRight = null;
                      });
                    });
                  }
                  setState(() {
                    activeOption = item;
                    isRight = currentIsRight;
                  });
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Color(0xFF202020),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  clipBehavior: Clip.hardEdge,
                  child: Stack(
                    children: showOption,
                  ),
                ),
              );
            }).toList(),
          ),
        ),
        Container(
            margin: EdgeInsets.only(bottom: 20),
            child: FocusWidget(
              autofocus: true,
              focusNode: focusNodes[1],
              onConfirm: widget.nextQuestion,
              onFocusChange: (bool value) {
                setState(() {});
              },
              child: Text('下一题',
                  style: TextStyle(
                    color: focusNodes[1].hasFocus
                        ? SchemeColor.seedColor.value
                        : null,
                  )),
            )),
      ],
    );
  }
}
